import gc
from utils import debug_info


class TimerController:
	# 定义定时器触发时间，单位：毫秒
	TIMER_PERIOD_1000 = 1000
	TIMER_PERIOD_2000 = 2100

	def __init__(self):
		import network
		from drivers.ds18b20 import DS18B20
		from machine import Timer, WDT, Pin
		from mqtt import MQTTClient

		self._PERIODIC = Timer.PERIODIC
		self._led = Pin(2, Pin.OUT, value=1)
		# self._watch_dog = WDT()
		self._sensor = DS18B20(4)
		self._mqtt_client = MQTTClient()
		self._station = network.WLAN(network.STA_IF)
		self._wifi_status_timer = Timer(0)
		self._led_blink_timer = Timer(1)
		self._get_temperature_timer = Timer(2)

		# self._watch_dog.feed()

	def deinit(self):
		self._get_temperature_timer.deinit()
		self._led_blink_timer.deinit()
		self._wifi_status_timer.deinit()
		self._led.value(1)
		self._sensor.deinit()
		self._mqtt_client.deinit()
		# self._watch_dog = None
		self._led = None

		gc.collect()

	def start_get_temperature_timer(self, period=5*60*1000):
		self._mqtt_client.start()

		self._get_temperature_timer.init(
			mode=self._PERIODIC,
			period=period,
			callback=self._get_temperature_cb
		)

		gc.collect()

	def _get_temperature_cb(self, timer):
		from config import Config

		# self._watch_dog.feed()

		try:
			temp = self._sensor.get_temperature()

			if temp is not None:
				debug_info("ds18b20 temp: %s" % temp)
			else:
				temp = 255
				print("get temp error")

			self._mqtt_client.publish_data_point(Config.MQTT.DATA_POINT_ID, temp=temp)

			gc.collect()
		except Exception as e:
			print(e)

	def start_wifi_status_timer(self):
		self._start_led_blink_timer()

		self._wifi_status_timer.init(
			mode=self._PERIODIC,
			period=self.TIMER_PERIOD_1000,
			callback=self._check_wifi_status_cb
		)

		gc.collect()

	def _check_wifi_status_cb(self, timer):
		if self._station.isconnected():
			self._led_blink_timer.deinit()
			self._led.value(1)

		gc.collect()

	def _start_led_blink_timer(self):
		self._led_blink_timer.init(
			mode=self._PERIODIC,
			period=self.TIMER_PERIOD_1000,
			callback=lambda timer: self._led.value(not self._led.value())
		)

		gc.collect()
